import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface PieHalfDonutProps {
    chartId?: string;
    width?: string;
    height?: string;
    title?: object;
    legend?: object;
    radius?: string[];
    center?: string[];
    angleRange?: number[];
    seriesData?: { value: number; name: string }[];
}

@customElement('lit-pie-half-donut')
export class LitPieHalfDonut extends LitElement {
    @property({type: String}) chartId: string = 'lit-pie-half-donut-chart';
    @property({type: String}) width: string = '600px';
    @property({type: String}) height: string = '400px';
    @property({type: Object}) title: any = {};
    @property({type: Object}) legend: any = {
        top: '5%',
        left: 'center'
    };
    @property({type: Array}) radius: string[] = ['40%', '70%'];
    @property({type: Array}) center: string[] = ['50%', '70%'];
    @property({type: Array}) angleRange: number[] = [180, 360];
    @property({type: Array}) seriesData: { value: number; name: string }[] = [
        {value: 1048, name: 'Search Engine'},
        {value: 735, name: 'Direct'},
        {value: 580, name: 'Email'},
        {value: 484, name: 'Union Ads'},
        {value: 300, name: 'Video Ads'}
    ];

    option: echarts.EChartsOption = {
        title: this.title,
        tooltip: {
            trigger: 'item'
        },
        legend: this.legend,
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: this.radius,
                center: this.center,
                // adjust the start and end angle
                startAngle: this.angleRange[0],
                endAngle: this.angleRange[1],
                data: this.seriesData,
            }
        ]
    };

    static styles = style;

    updated() {
        this.option.title = this.title;
        this.option.legend = this.legend;
        (this.option.series as any)[0].radius = this.radius;
        (this.option.series as any)[0].center = this.center;
        (this.option.series as any)[0].startAngle = this.angleRange[0];
        (this.option.series as any)[0].endAngle = this.angleRange[1];
        (this.option.series as any)[0].data = this.seriesData;
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width: ${this.width}; height: ${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-pie-half-donut': LitPieHalfDonut;
    }
}